#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <stdexcept>
#include <cstring>
#include "Function.hpp"

// 定义一个继承自Function的类
double TPF (double t, double x, int n) {
    return std::pow(std::max(t - x, 0.0), n);
}

// 截断幂差商函数
// t: 节点向量
// i: 节点索引
// x: 自变量
// n: 幂次
// k: 差商次数
double TPF_div(std::vector<double> t, double x, int i, int n, int k) {
    if(i + k >= t.size() || i < 0) {
        throw std::invalid_argument("The index is out of range.");
    }
    if (k == 0) {
        return TPF(t[i], x, n);
    }
    return (TPF_div(t, x, i + 1, n, k - 1) - TPF_div(t, x, i, n, k - 1)) / (t[i + k] - t[i]);
}
void print_TPF_div(int n, std::vector<double> knots){
    if (n + 3 > knots.size()){
        throw std::invalid_argument("The index is out of range.");
    }
    std::ofstream outfile("output/F" + std::to_string(n) + ".txt");
    for(int k = 0; k <= n + 1; ++k) {
        for(int i = 1; i + k <= n + 2; ++i) {
            for (double x = knots.front(); x <= knots.back(); x += 0.01) {
                //std::cout << x << " " << TPF_div(knots, x, i, n, k) << std::endl;
                outfile << x << " " << TPF_div(knots, x, i, n, k) << std::endl;
            }
            outfile << std::endl;
        }
    }
}
int main(int argc, char* argv[]) {
    std::vector<double> knots = {0, 1, 2, 3, 4}; // 给定节点
    print_TPF_div(1,knots);
    print_TPF_div(2,knots);
    return 0;
}